package com.jiangxiaofei.citycloud.activity.fleamarket;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.blankj.utilcode.util.EmptyUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.activity.user.LoginAcitivity;
import com.jiangxiaofei.citycloud.adapter.FleaGoodAdapter;
import com.jiangxiaofei.citycloud.adapter.FleaMenuGridAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.BannerBean;
import com.jiangxiaofei.citycloud.bean.FleaBannerImgBean;
import com.jiangxiaofei.citycloud.bean.FleaGoodBean;
import com.jiangxiaofei.citycloud.bean.FleaMenuBean;
import com.jiangxiaofei.citycloud.constants.BannerId;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FleaConstant;
import com.jiangxiaofei.citycloud.mvp.FleaPersenter;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.param.FleaChildGoodsParam;
import com.jiangxiaofei.citycloud.util.BannerViewHolder;
import com.jiangxiaofei.citycloud.view.SlidingGridView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.zhouwei.mzbanner.MZBannerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * @author: JiangXFei
 * @date: 2017/11/9 0009
 * @content: 二手交易 二级分类页面
 */

public class FleaMarketHaveActivity extends BaseActivity implements
        FleaConstant.GetFleaMenuView, FleaConstant.GetChildNewGoodsView,
        AdapterView.OnItemClickListener, MainConstant.GetBannerView {
    /**
     * @HAVETYPE 判断二级页面值
     */
    public static final String HAVETYPEID = "HAVETYPEID";


    @InjectView(R.id.img_back)
    ImageView imgBack;
    @InjectView(R.id.tv_search_type)
    TextView tvSearchType;
    @InjectView(R.id.et_search)
    TextView etSearch;
    @InjectView(R.id.img_publish)
    TextView imgPublish;
    @InjectView(R.id.banner)
    MZBannerView banner;
    @InjectView(R.id.recy_goodlist)
    RecyclerView recyGoodlist;
    @InjectView(R.id.linear_search)
    LinearLayout linearSearch;
    @InjectView(R.id.gv_menu)
    SlidingGridView gvMenu;
    @InjectView(R.id.srf_layout)
    SmartRefreshLayout srf;

    private List<FleaBannerImgBean> imgList = new ArrayList<>();
    private List<FleaMenuBean> menuList = new ArrayList<>();
    private List<FleaGoodBean> goodList = new ArrayList<>();
    private FleaConstant.GetFleanMenuPersenter fleanMenuPersenter;
    private int intExtra;
    private FleaGoodAdapter goodAdapter;
    private FleaMenuGridAdapter gridAdapter;
    private View popupView;
    private PopupWindow mPopupWindowPublish;
    private FleaChildGoodsParam param;
    private FleaConstant.GetChildNewGoodsPersenter getChildNewGoodsPersenter;
    private int page = 1;
    private MainConstant.GetBannerPersenter getBannerPersenter;
    private int bannerType;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_flea_have_layout);
        ButterKnife.inject(this);
        mContext = this;
        mActivity = this;
        Intent intent = getIntent();
        intExtra = intent.getIntExtra(HAVETYPEID, -1);
        bannerType = intent.getIntExtra(StringConstants.FLEABANNERTYPE, 0);
        if (this.intExtra == -1) {
            finish();
        }
        fleanMenuPersenter = new FleaPersenter(mContext, (FleaConstant.GetFleaMenuView) mActivity);
        fleanMenuPersenter.getFleaSencendMenu();
        initBannerImg();
        intGoodsRecy();
        initPopupPublish();
        initRftView();
        param = new FleaChildGoodsParam();
        param.setId(this.intExtra);
        param.setPage(page);
        getChildNewGoodsPersenter = new FleaPersenter(mContext, (FleaConstant.GetChildNewGoodsView) mActivity);
        getChildNewGoodsPersenter.getChildNewGoods();
        getBannerPersenter = new MainPersenter(mContext, (MainConstant.GetBannerView) mActivity);
        getBannerPersenter.getBanner();
    }

    /**
     * 初始化刷新框架
     */
    private void initRftView() {
        srf.setRefreshHeader(new MaterialHeader(this).setShowBezierWave(true));
        srf.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));

        srf.setOnLoadmoreListener(refreshlayout -> {
            refreshlayout.finishLoadmore(2000);
            page++;
            param.setPage(page);
            getChildNewGoodsPersenter.getChildNewGoods();
        });
        srf.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(2000);
            page = 1;
            goodList.clear();
            param.setPage(page);
            getChildNewGoodsPersenter.getChildNewGoods();
        });
    }

    private void initGridAdapter(int sum) {
        gridAdapter = new FleaMenuGridAdapter(mContext, menuList);
        gvMenu.setNumColumns(getCount(sum));
        gvMenu.setAdapter(gridAdapter);
        gvMenu.setOnItemClickListener(this);
    }


    /**
     * 初始化商品列表RECY
     */
    private void intGoodsRecy() {
        goodAdapter = new FleaGoodAdapter(R.layout.item_flea_good, goodList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
        recyGoodlist.setLayoutManager(gridLayoutManager);
        goodAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, FleaMarketGoodsDetailActivity.class);
                intent.putExtra(StringConstants.FLEAGOODID, Integer.valueOf(goodList.get(position).getId()));
                startActivity(intent);
            }
        });
        recyGoodlist.setAdapter(goodAdapter);
    }

    private int getCount(int sum) {
        int count = 1;
        if (sum % 4 == 0) {
            return 4;
        }
        if (sum % 3 == 0) {
            return 3;
        }
        if (count % 2 == 0) {
            return 2;
        }
        return count;
    }


    /**
     * 初始化banner图片
     */
    private void initBannerImg() {
        FleaBannerImgBean imgBean = new FleaBannerImgBean();
        imgBean.setImgurl("http://192.168.0.222/upload/client/banner.png");
        imgList.add(imgBean);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

    }

    @OnClick({R.id.img_back, R.id.img_publish, R.id.linear_search})
    public void bOnClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_publish:
                //发布
                if (EmptyUtils.isEmpty(Constants.userInfo)) {
                    startActivity(new Intent(this, LoginAcitivity.class));
                }else{
                    showPopup();
                }
                break;
            case R.id.linear_search:
                startActivity(new Intent(mActivity, FleaMarketSearchActivity.class));
                break;
            default:
                break;
        }
    }

    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public int getFleaMenu() {
        return intExtra;
    }

    @Override
    public void getFleaMainMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {

    }

    @Override
    public void getFleaSencendMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {
        initGridAdapter(fleaMenuBeans.size());
        menuList.clear();
        menuList.addAll(fleaMenuBeans);
        gridAdapter.notifyDataSetChanged();
    }

    @Override
    public void getFleaThreeMenuOnSuccess(List<FleaMenuBean> fleaMenuBeans) {

    }

    /**
     * 初始化发布popupWindow
     */
    private void initPopupPublish() {
        mPopupWindowPublish = new PopupWindow(mContext);
        popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_ios_buttom, null);
        showAnimation(popupView);
        mPopupWindowPublish.setContentView(popupView);
        mPopupWindowPublish.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindowPublish.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindowPublish.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindowPublish.setFocusable(true);
        mPopupWindowPublish.setOutsideTouchable(false);
        TextView tvGong = popupView.findViewById(R.id.tv_publish_gong);
        TextView tcXu = popupView.findViewById(R.id.tv_publish_xu);
        TextView tvCannel = popupView.findViewById(R.id.tv_cannel);
        tvGong.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FleaMarketHavePublishActivity.class));
        });
        tvCannel.setOnClickListener(v -> mPopupWindowPublish.dismiss());
        tcXu.setOnClickListener(v -> {
            mPopupWindowPublish.dismiss();
            startActivity(new Intent(mContext, FleaMarketNeedPublishActivity.class));
        });
    }

    private void showPopup() {
        showAnimation(popupView);
        mPopupWindowPublish.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0); // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.7f;
        mActivity.getWindow().setAttributes(lp);
        mPopupWindowPublish.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = mActivity.getWindow().getAttributes();
            lp1.alpha = 1f;
            mActivity.getWindow().setAttributes(lp1);
        });
    }

    private void showAnimation(View popView) {
        AnimationSet animationSet = new AnimationSet(false);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1.0f);
        alphaAnimation.setDuration(300);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        translateAnimation.setDuration(300);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(translateAnimation);
        popView.startAnimation(animationSet);
    }

    @Override
    public FleaChildGoodsParam getChildNewGoodsParam() {
        return param;
    }

    @Override
    public void childNewGoodsOnSuccess(List<FleaGoodBean> goodBeanList) {
        if (goodBeanList.size() > 0) {
            goodList.addAll(goodBeanList);
        }
        goodAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(mActivity, FleaMarketGoodsListActivity.class);
        intent.putExtra(StringConstants.FLEATYPEID, Integer.valueOf(menuList.get(position).getId()));
        startActivity(intent);
    }

    @Override
    public int getBannerParam() {
        switch (bannerType) {
            case 0:
                return BannerId.FLEAMENU1;
            case 1:
                return BannerId.FLEAMENU2;
            case 2:
                return BannerId.FLEAMENU3;
            case 3:
                return BannerId.FLEAMENU4;
            default:
                return BannerId.FLEAMENU1;
        }

    }

    @Override
    public void bannerSuccess(List<BannerBean> bannerBeans) {
        banner.setPages(bannerBeans, new BannerViewHolder(mContext));
        banner.start();
    }
}
